<template>
  <div class="container">
    <div class="head">
      <span class="title">0号柴油油价图</span>
      <el-form :inline="true" :model="form">
        <el-form-item label="">
          <el-select v-model="form.province" @change="getOilData(form.province)" placeholder="请选择地区">
            <el-option
              v-for="item in cities" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="exportData(form.province)">导出Excel</el-button>
        </el-form-item>
      </el-form>
    </div>
    <v-chart :options="graph1"/>
  </div>
</template>

<script>
  import axios from 'axios';
  import 'echarts/lib/chart/line';
  import 'echarts/lib/chart/bar';
  import 'echarts/lib/component/tooltip';
  import 'echarts/lib/component/dataZoom';
  import moment from 'moment';
  import _ from 'lodash';
  import {cities, s2ab, transformData} from '../utils/common';
  import {LinearGradient} from 'echarts/lib/util/graphic';
  import XLSX from 'xlsx';
  import FileSaver from 'file-saver';

  export default {
    data() {
      return {
        rawData: [],
        cities,
        form: {
          province: '天津',
        },
        graph1: {
          tooltip: {
            trigger: 'axis',
            position: function(pt) {
              return [pt[0], '10%'];
            },
          },
          title: {
            left: 'center',
            text: '大数据量面积图',
          },
          toolbox: {
            feature: {
              dataZoom: {
                yAxisIndex: 'none',
              },
              restore: {},
              saveAsImage: {},
            },
          },
          xAxis: {
            type: 'time',
            // boundaryGap: false,
            // data: date,
            splitNumber: 8,
            splitLine: {
              show: false,
            },
            axisLabel: {
              formatter: function(value, index) {
                return moment(value).format('YYYY-MM-DD');
              },
            },
          },
          yAxis: [
            {
              type: 'value',
              name: '油价（元/升）',
              min: 4,
              max: 9,
              interval: 0.5,
              axisLabel: {
                formatter: '{value}',
              },
              splitLine: {
                show: false,
              },
              // boundaryGap: [0, '100%'],
            }, {
              type: 'value',
              name: '油价涨幅',
              // boundaryGap: [0, '100%'],
              min: -2,
              max: 2,
              interval: 0.5,
              axisLabel: {
                formatter: '{value}%',
              },
            }],
          dataZoom: [
            // {
            //   type: 'inside',
            //   start: 0,
            //   end: 100,
            // },
            {
              type: 'slider',
              start: 0,
              end: 100,
              handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
              handleSize: '80%',
              handleStyle: {
                color: '#fff',
                shadowBlur: 3,
                shadowColor: 'rgba(0, 0, 0, 0.6)',
                shadowOffsetX: 2,
                shadowOffsetY: 2,
              },
              labelFormatter: {
                formatter: function(value, index) {
                  return moment(value).format('YYYY-MM-DD');
                },
              },
            },
          ],
          series: [
            {
              name: '价格',
              type: 'line',
              smooth: true,
              symbol: 'none',
              sampling: 'average',
              itemStyle: {
                color: '#e62a76',
              },
              data: [],
            },
            {
              name: '油价涨幅',
              type: 'bar',
              smooth: true,
              symbol: 'none',
              yAxisIndex: 1,
              barWidth: 5,
              sampling: 'average',
              // itemStyle: {
              //   color: '#774898',
              // },
              itemStyle: {
                normal: {
                  color: '#5eb547',
                },
                emphasis: {
                  color: '#00ff20',
                },
              },
              data: [],
            },
          ],
        },
      };
    },
    methods: {
      getOilData(city) {
        this.getOilDataAsync(city).then(() => {
        }).catch((err) => {
          console.error(err);
        });
      },
      async getOilDataAsync(city) {
        // const {data: {data: citys}} = await axios(
        //   'http://api.dataide.eastmoney.com/data/get_cn_yj_dq?order=asc&orderby=cityname&pageindex=1&pagesize=999');
        console.log(`city=${city}`);
        const {data: {data: rawData}} = await axios(
          `http://api.dataide.eastmoney.com/data/get_cn_yj_jh`, {
            params: {
              pagesize: 50000, pageindex: 1, order: 'desc', orderby: 'date', city: city,
            },
          });
        this.rawData = rawData;
        this.graph1.series[0].data = _.map(_.filter(rawData, x => x.v_0 && x.zde_0), x => [x.date, x.v_0]);
        this.graph1.series[1].data = _.map(_.filter(rawData, x => x.v_0 && x.zde_0), x => [x.date, x.zde_0]);
      },
      exportData(city) {
        this.exportDataAsync(city).then(res => {
          // console.log(res);
        }).catch(err => {
          console.error(err);
        });
      },
      async exportDataAsync(city) {
        const {data: {data: rawData}} = await axios(
          `http://api.dataide.eastmoney.com/data/get_cn_yj_jh`, {
            params: {
              pagesize: 50000, pageindex: 1, order: 'desc', orderby: 'date', city: city,
            },
          });
        // const data = transformData(rawData);
        const data = _.map(rawData, x => ({
          '日期': moment(x.date).format('YYYY-MM-DD'),
          '89#汽油价格': x.v_89,
          '89#汽油涨幅': x.zde_89,
          '92#汽油价格': x.v_92,
          '92#汽油涨幅': x.zde_92,
          '95#汽油价格': x.v_95,
          '95#汽油涨幅': x.zde_95,
          '0#柴油价格': x.v_0,
          '0#柴油涨幅': x.zde_0,
        }));
        const ws = XLSX.utils.json_to_sheet(data);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, 'data');
        var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'binary'});
        const blob = new Blob([s2ab(wbout)],
          {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
        FileSaver.saveAs(blob, `油价数据-${city}.xlsx`);
      },
    },
    mounted() {
      this.getOilData(this.form.province);
    },
  };
</script>

<style scoped>
  .container {
    height: 100%;
    width: 100%;
  }

  .echarts {
    height: calc(100% - 100px);
    width: 100%;
  }

  .head {
    height: 80px;
    width: 100%;
    /*overflow: hidden;*/
  }

  .container .head .title {
    line-height: 80px;
    margin-left: 20px;
    margin-right: 20px;
    font-size: x-large;
  }

  .container .el-select {
    width: 100px !important;
  }

  .container .head .el-form {
    position: absolute;
    display: inline-block;
    left: 340px;
    top: 25px;
    vertical-align: center;
  }

  .echarts div {
    height: 100% !important;
    width: 100% !important;
  }
</style>
